﻿using Lazy.Captcha.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MimeKit;
using SqlSugar;
using System.Net;
using WomanMotion.WebApi.Api.Utility;
using WomanMotion.WebApi.Infrastructure.Email;
using WomanMotion.WebApi.Infrastructure.UnifyResult;
using WomanMotion.WebApi.Model.Dtos.Carousel;

namespace WomanMotion.WebApi.Api.Controllers
{
    /// <summary>
    /// 验证码管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [XSSFilter]
    [ApiController]
    [DescriptionName("验证码管理")]
    public class CaptchaController : ControllerBase
    {
        private readonly ICaptcha _captcha;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="captcha"></param>
        public CaptchaController(ICaptcha captcha)
        {
            _captcha = captcha;
        }

        /// <summary>
        /// 获取验证码 返回文件流
        /// </summary>
        /// <param name="id">传入一个ID，验证的时候用此ID和验证码一起验证</param>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(typeof(SwaggerResultTemplate), (int)HttpStatusCode.OK)]
        [DescriptionName("获取验证码返回文件流")]
        [AllowAnonymous]
        public IActionResult GetCaptchaFile(string id)
        {
            var info = _captcha.Generate(id);
            // 有多处验证码且过期时间不一样，可传第二个参数覆盖默认配置。
            //var info = _captcha.Generate(id,120);
            var stream = new MemoryStream(info.Bytes);
            var base64Str = Convert.ToBase64String(info.Bytes);
            return File(stream, "image/gif");
        }

        /// <summary>
        /// 获取验证码 返回base64
        /// </summary>
        /// <param name="id">传入一个ID，验证的时候用此ID和验证码一起验证</param>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(typeof(SwaggerResultTemplate<CaptchVM>), (int)HttpStatusCode.OK)]
        [DescriptionName("获取验证码返回base64")]
        [AllowAnonymous]
        public IResultOutput GetCaptchaBase64(string id)
        {
            var info = _captcha.Generate(id);
            var res = new CaptchVM();
            res.base64 = Convert.ToBase64String(info.Bytes);
            return ResultOutput.Ok(res, "操作成功");
        }
    }

    /// <summary>
    /// base64验证码返回VM
    /// </summary>
    public class CaptchVM
    {
        /// <summary>
        /// 验证码base64编码
        /// </summary>
        public string? base64 { get; set; }
    }
}